package com.mrbeard.greenbroswer.acticity;

import android.Manifest;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;

import com.google.gson.Gson;
import com.mrbeard.greenbroswer.R;
import com.mrbeard.greenbroswer.entites.Device;
import com.mrbeard.greenbroswer.entites.Log;
import com.mrbeard.greenbroswer.services.GetMessageService;
import com.mrbeard.greenbroswer.utils.DeviceUtil;
import com.mrbeard.greenbroswer.utils.FileUtil;
import com.mrbeard.greenbroswer.utils.FormatUtil;
import com.mrbeard.greenbroswer.utils.PermissionListener;
import com.mrbeard.greenbroswer.utils.RabbitmqUtil;
import com.mrbeard.greenbroswer.utils.okhttputil.CallBackUtil;
import com.mrbeard.greenbroswer.utils.okhttputil.OkhttpUtil;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Response;


public class MainActivity extends BaseActivity {


    /**
     * 扫描跳转Activity RequestCode
     */
    public static final int REQUEST_CODE = 111;


    private String result;
    private Device device = new Device();
    private String logs;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //设置应用点击home键不退出应用
        if((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0){
            finish();
            return;
        }
        //判断权限
        permission();

        //定时发送日志
        sendLogs();

        //开启服务
        startService(new Intent(MainActivity.this, GetMessageService.class));
    }


    /**
     * 设置返回键与home键作用一样
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        PackageManager pm = getPackageManager();
        ResolveInfo homeInfo = pm.resolveActivity(
                new Intent(Intent.ACTION_MAIN)
                        .addCategory(Intent.CATEGORY_HOME), 0);
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            ActivityInfo ai = homeInfo.activityInfo;
            Intent startIntent = new Intent(Intent.ACTION_MAIN);
            startIntent.addCategory(Intent.CATEGORY_LAUNCHER);
            startIntent
                    .setComponent(new ComponentName(ai.packageName, ai.name));
            startActivitySafely(startIntent);
            return true;
        } else
            return super.onKeyDown(keyCode, event);
    }

    /**
     * 设置返回键与home键作用一样
     * @param intent
     */
    private void startActivitySafely(Intent intent) {
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        try {
            startActivity(intent);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(this, "null", Toast.LENGTH_SHORT).show();
        } catch (SecurityException e) {
            Toast.makeText(this, "null", Toast.LENGTH_SHORT).show();
        }
    }


    /**
     * 定时发送日志
     */
    private void sendLogs() {
        //创建Intent对象，action为ELITOR_CLOCK，附加信息为字符串“发送日志成功”
        Intent intent = new Intent("ELITOR_CLOCK");
        intent.putExtra("msg", "sendLogs");

        //定义一个PendingIntent对象，PendingIntent.getBroadcast包含了sendBroadcast的动作。
        //也就是发送了action 为"ELITOR_CLOCK"的intent
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent, 0);

        //AlarmManager对象,注意这里并不是new一个对象，Alarmmanager为系统级服务
        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);

        //设置闹钟从当前时间开始，每隔一小时s执行一次PendingIntent对象pi，注意第一个参数与第二个参数的关系
        // 5秒后通过PendingIntent pi对象发送广播
        am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),3600000, pi);
    }


    /**
     * 权限判断
     */
    private void permission() {
        requestRunPermisssion(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA, Manifest.permission.READ_PHONE_STATE}, new PermissionListener() {
            @Override
            public void onGranted() {
                //表示所有权限都授权了
                //Toast.makeText(MainActivity.this, "所有权限都授权了，可以搞事情了", Toast.LENGTH_SHORT).show();
                //开启服务
                startService(new Intent(MainActivity.this, GetMessageService.class));
            }

            @Override
            public void onDenied(List<String> deniedPermission) {
                for (String permission : deniedPermission) {
                    Toast.makeText(MainActivity.this, "被拒绝的权限：" + permission, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }


    /**
     * 绑定设备通过扫码
     *
     * @param view
     */
    public void bindDeviceByCamer(View view) {

        permission();
        //跳转到扫码页面
        Intent intent = new Intent(MainActivity.this, MyCamerActivity.class);
        startActivityForResult(intent, REQUEST_CODE);


    }


    /**
     * 处理二维码扫描结果
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == REQUEST_CODE) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    result = bundle.getString(CodeUtils.RESULT_STRING);

                    permission();
                    sendMessageBindDevice();


                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(MainActivity.this, "解析二维码失败", Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    /**
     * 发送信息绑定设备
     */
    private void sendMessageBindDevice() {
        //发送绑定请求
        String bindUrl = "http://www.scq725.cn:8080/greenbrowser/user/add_device";
        DeviceUtil deviceUtil = new DeviceUtil(this);
        Device device = deviceUtil.getDevice();
        Map map = new HashMap();
        map.put("userId", result);
        map.put("device", device);
        Gson gson = new Gson();
        OkhttpUtil.okHttpPostJson(bindUrl, gson.toJson(map), new CallBackUtil() {
            @Override
            public Object onParseResponse(Call call, Response response) {
                return null;
            }

            @Override
            public void onFailure(Call call, Exception e) {
                Toast.makeText(getApplicationContext(), "绑定失败，请联系管理员", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onResponse(Object response) {
                Toast.makeText(getApplicationContext(), "绑定成功！", Toast.LENGTH_LONG).show();
            }
        });
    }

    /**
     * 跳转到绑定页面
     *
     * @param view
     */
    public void gotoBindActivity(View view) {
        Intent intent = new Intent(this, BindDeviceActivity.class);
        startActivity(intent);
    }




}